{% extends 'crowdeye/base.html' %}

{% block body %}
<div class="camera-div">
    {% csrf_token %}
        {% for camera in cameras %}
            {{ ai_core_ip|json_script:forloop.counter0 }}
            <script>
                var value = JSON.parse(document.getElementById("{{forloop.counter0}}").textContent);
                console.log(value)
                window.setInterval(async function(){
                    const res = await fetch( window.location.protocol + "//" + window.location.host + '/api/get/{{ camera.node_id }}' )

                    const el = document.getElementById('info-{{forloop.counter0}}');
                    const data = await res.json()
                    el.innerHTML = JSON.stringify(data)
                    el.innerHTML = Math.abs(data.crossed_left - data.crossed_right)
                }, 2 * 1000);
            </script>

            <div class="row">
                <div class="col m12 l6">
                  <div class="card grey darken-3">
                    <div class="card-content white-text">
                      <span class="card-title">Node id: {{ camera.node_id }} / People in Store: <span id="info-{{forloop.counter0}}">Loading...</span></span>
                      <ul class="collapsible">
                        <li>
                            <div class="collapsible-header black-text">Collapse Stream</div>
                            <div class="collapsible-body">
                                Annotated stream:
                                <br />
                                <img class="image" id="img-{{camera.node_id}}" src="{{ ai_core_ip }}/stream/{{ camera.node_id }}/annotated" />
                            </div>
                        </li>
                    </ul>
                    <form action="" method="post">
                        {% csrf_token %}
                        <input type="hidden" value="{{ camera.node_id }}"  name="node_id" />
                        <p>Entry is:</p>
                        <p>
                          <label>
                            <input name="dir" type="radio" id="rtl" value="rtl" {% if camera.rtl %}checked{% endif %} />
                            <span>Right to Left</span>
                          </label>
                        </p>
                        <p>
                            <label>
                                <input name="dir" type="radio" id="ltr" value="ltr" {% if camera.rtl is not True %}checked{% endif %} />
                                <span>Left to Right</span>
                              </label>
                        </p>
                            <input type="submit" value="Save" class="btn btn-primary">
                      </form>
                    
                    </div>

                    <div class="card-action">
                        <a href="{{ camera.url }}" target="_blank" class="btn">Raw Camera Stream</a>
                        <button class="btn" onclick="startTrackingCoords({{forloop.counter0}}, {{camera.node_id}})">Move Line</button>
                        <button class="btn" onclick='fetch(window.location.protocol + "\/\/" + window.location.host + "/api/del/{{ camera.node_id }}")'>Reset Total</button> 
                        <form action="{% url 'camera-delete' camera.pk %}" method="post" style="display: inline;">
                            {% csrf_token %}
                            <input type="submit" value="Delete" class="btn red darken-2">
                        </form>

                    </div>
                  </div>
                </div>
              </div>        
                <br />



        {% empty %}
            None, add one
        {% endfor %}

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var elems = document.querySelectorAll('.collapsible');
            var instances = M.Collapsible.init(elems, {});
        });
                
        var total_clicks = 0;
        var pos = [];
        var node_id;

        function startTrackingCoords(num, node) {
            node_id = node
            total_clicks = 0;
            pos = [];
            console.log("Start", num);
            alert("Click on the first than the second point on the annoted image")
            const res = document.getElementsByClassName('image');
            res[num].addEventListener('click', printPosition);
        }

        function getPosition(e) {
            var rect = e.target.getBoundingClientRect();
            var x = e.clientX - rect.left;
            var y = e.clientY - rect.top;
            return {
              x,
              y
            }
        }
          
        function printPosition(e) {
            total_clicks = total_clicks + 1;
            var position = getPosition(e);
            pos.push([position.x,  position.y])
            if (total_clicks >= 2) 
            {
                console.log("Done", pos)
                const res = document.getElementsByClassName('image');
                for (var i = 0; i < res.length; i++)
                {
                    res[i].removeEventListener('click', printPosition)
                }
                pos.push(node_id)
                const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
                const request = new Request(
                    window.location.protocol + "//" + window.location.host + '/api/cl/',
                    {
                        method: "POST",
                        headers: {'X-CSRFToken': csrftoken},
                        body: JSON.stringify(pos)
                    }
                );
                fetch(request, {
                    mode: 'same-origin'  // Do not send CSRF token to another domain.
                }).then(function(response) {
                    // ...
                });


            }
        }
          
    </script>
    
    
    <br />    
    
</div>

<div class="fixed-action-btn" id="add-btn">
    <a id="menu" class="waves-effect  teal btn-large btn btn-floating modal-trigger" href="#modal1">
        <i class="material-icons">add</i>
    </a>    
</div>


<div class="tap-target teal white-text" data-target="menu">
    <div class="tap-target-content">
      <h5>Add a camera</h5>
      <p>Use this button to add a camera to your list</p>
    </div>
  </div>

<div id="modal1" class="modal">
    <div class="modal-content">
      <h4>Add a camera</h4>
      <form method="POST">
        {% csrf_token %}
        <div class="input-group mb-3">
            <input type="text" class="form-control" placeholder="Camera URL" name="url" id="url-field" required>
        </div>
        
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

    </div>
    <div class="modal-footer">
      <a href="#!" class="modal-close waves-effect btn-flat">Cancel</a>
    </div>
  </div>
          

<script>


    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.modal');
        var instances = M.Modal.init(elems, {});
    
        var elems = document.querySelectorAll('.tap-target');
        var instances = M.TapTarget.init(elems, {});

        console.log(instances)
        {% for camera in cameras %}
        {% empty %}
        instances[0].open();
        {% endfor %}


    });


    

</script>  
{% endblock %}


{% block extracss %}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
{% endblock %}